<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="水表业务编号" style="width: 300px;">
              <el-input v-model="searchForm.meterCode" placeholder="水表业务编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="水表名称" style="width: 300px;">
              <el-input v-model="searchForm.meterName" placeholder="水表名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="水表卡号" style="width: 300px;">
              <el-input v-model="searchForm.meterCard" placeholder="水表卡号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="6">
            <el-form-item label="状态" style="width: 300px;">
              <el-select v-model="searchForm.status" placeholder="状态">
                <el-option label="全部" value=""></el-option>
                <el-option label="正常" value="0"></el-option>
                <el-option label="报警" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属模板" style="width: 300px;">
              <el-select v-model="searchForm.templateId" placeholder="所属模板">
                <el-option v-for="item in templateList" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </el-card>

    <el-card class="mt-2">
      <!-- 操作按钮 -->
      <el-row :getter="20">
        <el-col :span="12">
          <div>
            <el-button type="primary" @click="handleAdd" icon="Plus">新增</el-button>
          </div>
        </el-col>
        <el-col :span="12" class="flex-end">
          <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="loadData"
            :columns="columns"></right-toolbar>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <div class="mt-2">
        <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
          <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
          <!-- <el-table-column prop="meterId" label="水表ID" align="center" v-if="columns[0].visible"></el-table-column> -->
          <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
          <el-table-column prop="meterName" label="水表名称" align="center" v-if="columns[1].visible"></el-table-column>
          <el-table-column prop="meterCode" label="水表业务编号" align="center" v-if="columns[2].visible"></el-table-column>
          <el-table-column prop="meterCard" label="水表卡号" align="center" v-if="columns[3].visible"></el-table-column>
          <el-table-column prop="linePosition" label="水表位置" align="center" v-if="columns[10].visible">
            <template #default="{ row }">
              <div>{{ row.geoPosition ? row.geoPosition.slice(0, 10) + '...' : "" }}</div>

            </template>
          </el-table-column>
          <el-table-column prop="caliber" label="水表口径" align="center" v-if="columns[4].visible"></el-table-column>
          <el-table-column prop="templateId" label="模板id" align="center" v-if="columns[11].visible"></el-table-column>
          <el-table-column prop="sn" label="设备编号" align="center" v-if="columns[12].visible"></el-table-column>
          <el-table-column prop="installAddress" label="安装地址" align="center"
            v-if="columns[5].visible"></el-table-column>
          <el-table-column prop="installDate" label="安装日期" align="center" v-if="columns[6].visible">
            <template #default="{ row }">
              {{ formatDate(row.installDate) }}
            </template>
          </el-table-column>
          <!-- 新增管网图片列 -->
          <el-table-column prop="fileId" label="管网图片" align="center" v-if="columns[10].visible">
            <template #default="{ row }">
              <el-image style="width: 30px; height: 30px" :src="getImageUrl(row.meterImage)"
                :preview-src-list="[getImageUrl(row.meterImage)]" fit="cover" preview-teleported>
                <template #error>
                  <div class="image-slot">
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" v-if="columns[7].visible">
            <template #default="{ row }">
              <el-tag :type="row.status == 0 ? 'success' : 'danger'">
                {{ row.status == 0 ? '正常' : '报警' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" v-if="columns[8].visible">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" v-if="columns[9].visible">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row.meterId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :close-on-click-modal="false">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="水表名称" prop="meterName">
              <el-input v-model="formData.meterName" placeholder="请输入水表名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="水表业务编号" prop="meterCode">
              <el-input v-model="formData.meterCode" placeholder="如14号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="水表卡号" prop="meterCard">
              <el-input v-model="formData.meterCard" placeholder="如14号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="水表口径" prop="caliber">
              <el-input v-model="formData.caliber" placeholder="请输入水表口径"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安装地址" prop="installAddress">
              <el-input v-model="formData.installAddress" placeholder="详细到门牌号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装日期" prop="installDate">
              <el-date-picker v-model="formData.installDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编号" prop="sn">
              <el-input v-model="formData.sn" placeholder="请输入设备编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态">
                <el-option label="正常" :value="0"></el-option>
                <el-option label="报警" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联管道ID" prop="pipeId">
              <el-input v-model="formData.pipeId" placeholder="关联管道ID"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="所属模板" style="width: 300px;">
              <el-select v-model="formData.templateId" placeholder="所属模板">
                <el-option v-for="item in templateList" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="纬度，经度" prop="geoPosition">
              <el-input v-model="formData.geoPosition" placeholder="纬度，经度"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="水表图片" prop="fileId">
          <UploadFile ref="uploadFileRef" @success="handleUploadSuccess" :files="formData.meterImage" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
  getMeterList,
  getMeterDetail,
  addMeter,
  updateMeter,
  deleteMeter,
  getIotDeviceTemplateList
} from '@/api/park/device/info'
import UploadFile from '@/components/UploadFile/index.vue'

const uploadFileRef = ref(null)

// 模板下拉列表相关
const templateList = ref()
const getTemplateList = async () => {
  const res = await getIotDeviceTemplateList()
  templateList.value = res.data.map(item => ({
    label: item.name,
    value: item.id
  }));
}
// 搜索表单
const searchForm = reactive({
  meterCode: '',
  meterName: '',
  meterCard: '',
  status: ''
})
const showSearch = ref(true);

// 表格数据
const tableData = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增水表设备')
const formRef = ref(null)
const formData = reactive({

})

// 获取图片URL
const getImageUrl = (pipeImage) => {
  if (!pipeImage) return null;
  return import.meta.env.VITE_APP_IMAGE_URL + pipeImage;
}

// 表单验证规则
const rules = reactive({
  meterName: [{ required: true, message: '请输入水表名称', trigger: 'blur' }],
  meterCode: [{ required: true, message: '请输入水表业务编号', trigger: 'blur' }],
  meterCard: [{ required: true, message: '请输入水表卡号', trigger: 'blur' }],
  caliber: [{ required: true, message: '请输入水表口径', trigger: 'blur' }],
  installAddress: [{ required: true, message: '请输入安装地址', trigger: 'blur' }],
  installDate: [{ required: true, message: '请选择安装日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  sn: [{ required: true, message: '请输入设备编号', trigger: 'change' }]
})


// 列显隐信息
const columns = ref([
  { key: 0, label: `水表ID`, visible: true },
  { key: 1, label: `水表名称`, visible: true },
  { key: 2, label: `水表业务编号`, visible: true },
  { key: 3, label: `水表卡号`, visible: true },
  { key: 4, label: `水表口径`, visible: true },
  { key: 11, label: `模板id`, visible: true },
  { key: 12, label: `设备编号`, visible: true },
  { key: 5, label: `安装地址`, visible: true },
  { key: 6, label: `安装日期`, visible: true },
  { key: 7, label: `状态`, visible: true },
  { key: 8, label: `创建时间`, visible: true },
  { key: 9, label: `操作`, visible: true },
  { key: 10, label: `纬度,经度`, visible: true },
])

// 多选
const multipleSelection = ref([])

// 加载数据
const loadData = async () => {
  try {
    const params = {
      ...searchForm,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    const res = await getMeterList(params)
    tableData.value = res.rows;
    pagination.total = res.total;
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增水表设备'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑水表设备'
  try {
    const res = await getMeterDetail(row.meterId)
    Object.assign(formData, res.data)
    console.log(formData);

    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该水表设备吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMeter(id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 多选变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 重置表单
const resetForm = () => {
  uploadFileRef.value?.clearFileList()
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.keys(formData).forEach(key => {
    if (key !== 'status') {
      formData[key] = ''
    } else {
      formData[key] = '0'
    }
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (dialogTitle.value === '新增水表设备') {
      await addMeter(formData)
      ElMessage.success('新增成功')
    } else {
      await updateMeter(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error !== 'validate') {
      ElMessage.error('操作失败')
    }
  }
}

// 上传成功
const handleUploadSuccess = (ids) => {
  formData.fileId = ids[0];
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return date.split('T')[0]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return dateTime.replace('T', ' ')
}

// 初始化加载数据
onMounted(() => {
  loadData()
  getTemplateList()
})
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}
</style>